package com.walk.zworld.ui.fragment

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Environment
import android.provider.MediaStore
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.walk.zworld.R
import com.walk.zworld.mvvm.Constant
import com.walk.zworld.mvvm.viewModel.MyViewModel
import com.walk.zworld.ui.activity.LoginActivity
import com.walk.zworld.utils.FileUtils
import com.walk.zworld.view.BottomDialog
import com.walk.zworld.view.MyDialog
import com.walk.zworld.webView.captureImage
import com.walk.zworld.webView.selectImage
import com.base.lib.base.utils.MyMMKV.Companion.mmkv
import com.base.lib.base.utils.SettingUtil
import com.base.lib.base.utils.ext.view.showToast
import com.base.lib.base.view.BaseMvvmFragment
import com.base.lib.base.widget.PaintView
import com.base.lib.xdialog.anno.BottomButtonStyle
import com.base.lib.xdialog.anno.DialogStyle
import com.base.lib.xdialog.bean.textStyle
import com.base.lib.xdialog.components.simpleTitle
import com.base.lib.xdialog.dialog.content.IDialogContent
import com.base.lib.xdialog.dialog.createDialog
import com.base.lib.xdialog.dialog.footer.simpleFooter
import com.walk.zworld.ui.activity.my.AboutActivity
import com.walk.zworld.ui.activity.my.LaterReadActivity
import com.walk.zworld.ui.activity.my.MyCollectActivity
import com.walk.zworld.ui.activity.my.MyScoreActivity
import com.walk.zworld.ui.activity.my.MyShareActivity
import com.walk.zworld.ui.activity.my.ReadRecordActivity
import com.walk.zworld.ui.activity.my.SystemActivity
import com.walk.zworld.ui.activity.my.TodoActivity
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException

class MyFragment : BaseMvvmFragment<MyViewModel>(), View.OnClickListener {

    companion object {
        fun newsInstance() = MyFragment()
    }

    private lateinit var bottomDialog: BottomDialog
    private lateinit var logoutDialog: MyDialog
    private lateinit var refreshLayout: SmartRefreshLayout
    private val headType = "head"
    private val bgType = "backGround"
    private var type = ""

    private lateinit var tv_un_todo: TextView
    private lateinit var my_rank_num: TextView
    private lateinit var tv_name: TextView
    private lateinit var head_pic: ImageView
    private lateinit var iv_bg_img: ImageView
    private lateinit var ll_my_collect: View
    private lateinit var ll_score: View
    private lateinit var ll_my_share: View
    private lateinit var ll_my_logout: View
    private lateinit var iv_todo: View
    private lateinit var ll_my_system: View
    private lateinit var ll_my_about: View
    private lateinit var ll_my_laterRead: View
    private lateinit var ll_my_readRecord: View

    override fun onBindViewModel(): Class<MyViewModel> = MyViewModel::class.java

    override fun onBindLayout(): Int = R.layout.fragment_my

    override fun initView(view: View) {
        refreshLayout = findViewById(R.id.swipeRefreshLayout_my)
        refreshLayout.run {
            setRefreshHeader(findViewById(R.id.ch_header_my))
            setOnRefreshListener { startHttp() }
        }
        refreshLayout.setEnableLoadMore(false)

        tv_name = findViewById(R.id.tv_name)
        head_pic = findViewById(R.id.head_pic)
        iv_bg_img = findViewById(R.id.iv_bg_img)
        ll_my_collect = findViewById(R.id.ll_my_collect)
        ll_score = findViewById(R.id.ll_score)
        ll_my_share = findViewById(R.id.ll_my_share)
        ll_my_logout = findViewById(R.id.ll_my_logout)
        iv_todo = findViewById(R.id.iv_todo)
        ll_my_system = findViewById(R.id.ll_my_system)
        ll_my_about = findViewById(R.id.ll_my_about)
        ll_my_laterRead = findViewById(R.id.ll_my_laterRead)
        ll_my_readRecord = findViewById(R.id.ll_my_readRecord)
        my_rank_num = findViewById(R.id.my_rank_num)
        tv_un_todo = findViewById(R.id.tv_un_todo)
    }

    override fun initData() {
        tv_name.setOnClickListener(this)
        head_pic.setOnClickListener(this)
        iv_bg_img.setOnClickListener(this)
        ll_my_collect.setOnClickListener(this)
        ll_score.setOnClickListener(this)
        ll_my_share.setOnClickListener(this)
        ll_my_logout.setOnClickListener(this)
        iv_todo.setOnClickListener(this)
        ll_my_system.setOnClickListener(this)
        ll_my_about.setOnClickListener(this)
        ll_my_laterRead.setOnClickListener(this)
        ll_my_readRecord.setOnClickListener(this)
        LiveEventBus.get(Constant.IS_LOGIN, Boolean::class.java).observe(this) {
            if (it) {
                startHttp()
            } else {
                tv_name.text = resources.getString(R.string.my_login)
                my_rank_num.text = resources.getString(R.string.my_score)
            }
        }
        LiveEventBus.get("myBadge", Boolean::class.java).observe(this) {
            if (!SettingUtil.getIsShowBadge()) {
                tv_un_todo.visibility = View.GONE
                return@observe
            }
            if (it && mmkv.decodeBool(Constant.IS_LOGIN, false)) {
                tv_un_todo.visibility = View.VISIBLE
            } else tv_un_todo.visibility = View.GONE
        }
        setImage(mmkv.decodeString("HeadPic", "")?.let { File(it) })
        if (mmkv.decodeString("bgHeadPic", "") != "")
            setBgImage(mmkv.decodeString("bgHeadPic", "")?.let { File(it) })
    }

    private fun startHttp() {
        if (mmkv.decodeBool(Constant.IS_LOGIN, false)) {
            getTodoBadge()
            tv_name.text = mmkv.decodeString(Constant.USERNAME_KEY, resources.getString(R.string.my_login))
            my_rank_num.text = "${resources.getString(R.string.my_score)}(${mmkv.decodeString(
                Constant.USERNAME_COIN_COUNT)})"
            mViewModel.getUserInfo().observe(this) {
                refreshLayout.finishRefresh()
                tv_name.text = it.username
                my_rank_num.text = "${resources.getString(R.string.my_score)}(${it.coinCount})"
                mmkv.encode(Constant.USERNAME_COIN_COUNT, it.coinCount.toString())
                mmkv.encode(Constant.USERNAME_KEY, it.username)
                mmkv.encode(Constant.SCORE_UNM, it.coinCount)
            }
        } else {
            if (refreshLayout.isRefreshing) refreshLayout.finishRefresh()
            tv_name.text = resources.getString(R.string.my_login)
            my_rank_num.text = resources.getString(R.string.my_score)
        }
    }

    private fun getTodoBadge() {
        val map = mutableMapOf<String, Any>()
        map["status"] = 0
        mViewModel.getTodoList(1, map).observe(this) {
            hideInitLoadView()
            it.datas.let { todoList ->
                if (todoList.size > 0) {
                    tv_un_todo.visibility = View.VISIBLE
                    LiveEventBus.get("myBadge").post(true)
                } else {
                    tv_un_todo.visibility = View.GONE
                    LiveEventBus.get("myBadge").post(false)
                }
            }
        }
    }

    private fun setImage(file: File?) {
        FileUtils.loadByNoCache(context, file, head_pic)
    }

    private fun setBgImage(file: File?) {
        FileUtils.loadByNoCache(context, file, iv_bg_img)
    }

    override fun onClick(v: View?) {
        when (v) {
            tv_name -> {
                if (!mmkv.decodeBool(Constant.IS_LOGIN, false))
                    startActivity(Intent(activity, LoginActivity::class.java))
            }
            ll_score -> {
                if (mmkv.decodeBool(Constant.IS_LOGIN, false)) {
                    startActivity(Intent(activity, MyScoreActivity::class.java))
                } else {
                    startActivity(Intent(activity, LoginActivity::class.java))
                }
            }
            ll_my_collect -> {
                if (mmkv.decodeBool(Constant.IS_LOGIN, false)) {
                    startActivity(Intent(activity, MyCollectActivity::class.java))
                } else {
                    startActivity(Intent(activity, LoginActivity::class.java))
                }
            }
            ll_my_share -> {
                if (mmkv.decodeBool(Constant.IS_LOGIN, false)) {
                    startActivity(Intent(activity, MyShareActivity::class.java))
                } else {
                    startActivity(Intent(activity, LoginActivity::class.java))
                }
            }
            head_pic -> showPhotoDialog(headType)
            iv_bg_img -> showPhotoDialog(bgType)
            ll_my_logout -> {
                if (mmkv.decodeBool(Constant.IS_LOGIN, false)) {
                    if (!this::logoutDialog.isInitialized) {
                        logoutDialog = MyDialog(requireActivity())
                        logoutDialog.run {
                            setDialogText("是否确认退出登录?")
                            setClickListener { v ->
                                when (v.id) {
                                    R.id.tv_dialog_sure -> {
                                        if (logoutDialog.isShowing) logoutDialog.dismiss()
                                        mViewModel.logout().observe(this@MyFragment) {
                                            mmkv.encode(Constant.IS_LOGIN, false)
                                            LiveEventBus.get(Constant.IS_LOGIN).post(false)
                                            LiveEventBus.get("myBadge").post(false)
                                        }
                                    }
                                    R.id.tv_dialog_cancle -> {
                                        if (logoutDialog.isShowing) logoutDialog.dismiss()
                                    }
                                }
                            }
                            show()
                        }
                    } else logoutDialog.show()
                } else toast("当前未登录!")
            }
            iv_todo -> {
                if (mmkv.decodeBool(Constant.IS_LOGIN, false)) {
                    startActivityForResult(
                        Intent(activity, TodoActivity::class.java),
                        Constant.FROM_TODO
                    )
                } else {
                    startActivity(Intent(activity, LoginActivity::class.java))
                }
            }
            ll_my_system -> startActivity(Intent(activity, SystemActivity::class.java))
            ll_my_about -> startActivity(Intent(activity, AboutActivity::class.java))
            ll_my_laterRead -> startActivity(Intent(activity, LaterReadActivity::class.java))
            ll_my_readRecord -> startActivity(Intent(activity, ReadRecordActivity::class.java))
        }
    }

    private fun showPhotoDialog(imgType: String) {
        type = imgType
        if (this::bottomDialog.isInitialized) bottomDialog.show()
        else {
            bottomDialog = BottomDialog(
                requireActivity(), {
                    when (it.id) {
                        R.id.tv_take_photo -> {
                            if (this::bottomDialog.isInitialized && bottomDialog.isShowing) {
                                bottomDialog.dismiss()
                                captureImage(requireActivity())
                            }
                        }
                        R.id.tv_from_album -> {
                            if (this::bottomDialog.isInitialized && bottomDialog.isShowing) {
                                bottomDialog.dismiss()
                                selectImage(requireActivity())
                            }
                        }
                        R.id.tv_from_write -> {
                            if (this::bottomDialog.isInitialized && bottomDialog.isShowing) {
                                bottomDialog.dismiss()
                                var paintView: PaintView = PaintView(requireActivity())
                                createDialog {
                                    withHeight(600)
                                    withStyle(DialogStyle.STYLE_WRAP)
                                    withTitle(simpleTitle("自主画板"))
                                    withContent(object: IDialogContent {
                                        override fun getView(ctx: Context): View {
                                            val linearLayout = LinearLayout(ctx);
                                            linearLayout.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
                                            linearLayout.gravity = Gravity.CENTER
                                            paintView.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
                                            linearLayout.addView(paintView)
                                            return linearLayout
                                        }
                                    })
                                    withBottom(simpleFooter {
                                        withStyle(BottomButtonStyle.BUTTON_STYLE_DOUBLE)
                                        withLeft("取消")
                                        withRight("确定")
                                        withDivider(Color.LTGRAY)
                                        withLeftStyle(textStyle {
                                            withColor(Color.GRAY)
                                        })
                                        withRightStyle(textStyle {
                                            withColor(Color.RED)
                                        })
                                        onLeft { dlg, _, _ ->
                                            dlg.dismiss()
                                        }
                                        onRight { _1, _, content ->
                                            val savePath = paintView.saveBitmap();
                                            savePath.showToast()
                                            if (type == headType){
                                                mmkv.encode("HeadPic", savePath)
                                                val file = File(savePath)
                                                if (file.exists()){
                                                    setImage(file)
                                                }
                                            }
                                            if (bgType == type){
                                                mmkv.encode("bgHeadPic", savePath)
                                                val file = File(savePath)
                                                if (file.exists()){
                                                    setBgImage(file)
                                                }
                                            }
                                            _1.dismiss()
                                        }
                                    })
                                }.show(requireActivity().supportFragmentManager, "normal_top")
                            }
                        }
                        R.id.tv_cancle -> {
                            if (this::bottomDialog.isInitialized && bottomDialog.isShowing) bottomDialog.dismiss()
                        }
                    }
                })
            bottomDialog.show()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //打开图片
        if (resultCode == Activity.RESULT_OK && resultCode != Activity.RESULT_CANCELED) {
            when (requestCode) {
                Constant.IMAGE_CAPTURE -> {//拍照返回
                    val pathName = activity?.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
                        .toString() + "/" + Constant.HEAD_PIC_PATH
                    val bitmap = BitmapFactory.decodeFile(pathName) ?: return
                    val newBitmap = FileUtils.compressImage(bitmap) ?: bitmap//压缩失败使用原图
                    // 由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
                    bitmap.recycle()
                    val picFileName: File?
                    if (type == headType) {
                        picFileName = FileUtils.saveBitmap(newBitmap)
                        setImage(picFileName)
                        mmkv.encode("HeadPic", picFileName?.path)
                    } else {
                        picFileName = FileUtils.saveBitmap(newBitmap, Constant.MY_BG_PIC_PATH)
                        setBgImage(picFileName)
                        mmkv.encode("bgHeadPic", picFileName?.path)
                    }
                    // 由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
                    bitmap.recycle()
                }
                Constant.IMAGE_SELECT -> {
                    val resolver = activity?.contentResolver
                    // 照片的原始资源地址
                    val originalUri = data?.data
                    try {
                        // 使用ContentProvider通过URI获取原始图片
                        val photo = MediaStore.Images.Media.getBitmap(resolver, originalUri)
                        if (photo != null) {
                            // 为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
                            val newBitmap = FileUtils.compressImage(photo) ?: photo//压缩失败使用原图
                            // 释放原始图片占用的内存，防止out of memory异常发生
                            photo.recycle()
                            val picFileName: File?
                            if (type == headType) {
                                picFileName = FileUtils.saveBitmap(newBitmap)
                                setImage(picFileName)
                                mmkv.encode("HeadPic", picFileName?.path)
                            } else {
                                picFileName = FileUtils.saveBitmap(newBitmap, Constant.MY_BG_PIC_PATH)
                                setBgImage(picFileName)
                                mmkv.encode("bgHeadPic", picFileName?.path)
                            }
                        }
                    } catch (e: FileNotFoundException) {
                        e.printStackTrace()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
                Constant.FROM_TODO -> getTodoBadge()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (this::bottomDialog.isInitialized && bottomDialog.isShowing) bottomDialog.dismiss()
    }
}